package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.qf.entity.Orders;
import com.qf.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private IOrderService orderService;

    @RequestMapping("/alipay")
    public String alipay(String oid, HttpServletResponse response){
        System.out.println("接收到支付宝的请求：" + oid);
        Orders orders = orderService.getById(oid);

        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                "2016102600762741",
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCFllibTZI77DBEtiAmeFxXk7VVxe3m4oH9150Fda9fmcTwh4iWT4Jk3H+XuABG1I+ge7Xj0sjnoWq6WOJve4Pj3r1Ldl7QDiOz7bTW+qynMkWA7m+8UQMXFRhQ+NzhwIyOg1YOIScYamb493fXt2chepWyB7Pa0aw8qpdUGB2+kWd2KQjI6c1pTAOol/9t5aFuct8iZHWGTouy//rip6+r/SeNRJHved+MwlqCnVyTq6dXDNz5m2qHiFynQMvblTVcmMVMAcb+xhV6MfYt7C77LmnE9/BtU5Vmu5roIQN0Pr/tIqp2d8ZZcK+egefDdO9Jsl+HZqRfTPveB8/3RvUrAgMBAAECggEAfQ6KVJkB1Ob/KNP2tQzoJXQ5xdpNJF/XoXM/o+TQEIc7PpEi5NP6FcH2EGpImAZVjr9BP84MFguehmS/Ve4jQic6vnJJwCv8cGyPZtG037DIMDMGlxyf7/Pnl6Xh4dUHwEJjRUbz+n9hdqD0qBUhjs3bZZagYLD4tLJeiHMrJUJPDWzKLOnJwjPQUNeeUQg3s0NjfMu/vatwhvBh2rZOKqw2fUyOs+tos3mDAx7bu9LqaifJfMUT1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myh9zEyWlz5p1zrahRahbXAfCfSqshSNfqOmAQzSHRVjCqjsAw1jyqrXaPdKBmr90DIpIxmIyKXv4GGAkPyJ/6FTFY99uhpiq0qadD/uSzQsefWo0aTvP/65zi3eof7TcZ32oWpwIDAQAB",
                "RSA"); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://www.baidu.com");
        alipayRequest.setNotifyUrl("http://www.baidu.com");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":\""+ oid +"\"," +
                " \"total_amount\":\""+ orders.getAllPrice() + "\"," +
                " \"subject\":\""+ oid +"\"," +
                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
